<template>
    <div class="adminRole">
        <el-form ref="formRef" :inline="true" :model="form" class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px]"
            style="position: relative;" :class="{ 'searchBarZoomClass': searchBarZoom }">
            <el-button type="info" :icon="searchBarZoom ? useRenderIcon(EpArrowDownBold) : useRenderIcon(EpArrowUpBold)"
                @click="changeHeight" class="widthExpansionAndContractionBut">
            </el-button>
            <el-form-item label="任务编码：" prop="code">
                <el-input v-model="form.code" placeholder="请输入任务编码" clearable class="!w-[230px]" />
            </el-form-item>
            <el-form-item label="第三方任务编码：" prop="outCode">
                <el-input v-model="form.outCode" placeholder="请输入第三方任务编码" clearable class="!w-[190px]" />
            </el-form-item>
            <el-form-item label="托盘编码：" prop="trayCode">
                <el-input v-model="form.trayCode" placeholder="请输入托盘编码" clearable class="!w-[230px]" />
            </el-form-item>
            <el-form-item label="车辆名称：" prop="agvid">
                <el-select v-model="form.agvid" clearable placeholder="请选择车辆名称" class="!w-[230px]">
                    <el-option v-for="item in agvSelect" :key="item.AgvId" :label="item.AgvName" :value="item.AgvId" />
                </el-select>
            </el-form-item>
            <el-form-item label="任务类型：" prop="jobtype">
                <el-select v-model="form.jobtype" filterable clearable placeholder="请选择任务类型" class="!w-[230px]">
                    <el-option v-for="item in taskOptions" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="任务状态：" prop="status">
                <el-select v-model="form.status" clearable multiple placeholder="请选择状态" class="!w-[230px]">
                    <el-option v-for="item in statusSelect" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="起点货位：" prop="startloc">
                <el-input v-model="form.startloc" placeholder="请输入起点货位" clearable class="!w-[230px]" />
            </el-form-item>
            <el-form-item label="终点货位：" prop="endloc">
                <el-input v-model="form.endloc" placeholder="请输入终点货位" clearable class="!w-[230px]" />
            </el-form-item>
            <el-form-item label="创建时间：" prop="dateRange" style="font-weight: 700;">
                <!-- <el-date-picker v-model="form.dateRange" type="daterange" range-separator="-" start-placeholder="开始日期"
          end-placeholder="结束日期" class="!w-[230px]" @change="pickerChange" /> -->
                <el-date-picker v-model="form.dateRange" type="datetimerange" start-placeholder="开始日期"
                    end-placeholder="结束日期" format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd"
                    time-format="A hh:mm:ss" class="!w-[230px]" @change="pickerChange" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :icon="useRenderIcon(Search)" :loading="loading" @click="onSearch">
                    搜索
                </el-button>
                <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
                    重置
                </el-button>
            </el-form-item>
        </el-form>

        <PureTableBar title="任务管理" :columns="columns" @refresh="onSearch" :key="tableKey">
            <template #buttons>
                <el-button type="primary" :icon="useRenderIcon(AddFill)" @click="openDialog('搬运')">
                    搬运
                </el-button>
                <el-button type="primary" :icon="useRenderIcon(AddFill)" @click="agvTask('移动', 0)">
                    移动
                </el-button>
                <el-button type="primary" :icon="useRenderIcon(AddFill)" @click="agvTask('充电', 2)">
                    充电
                </el-button>
                <el-button type="primary" :icon="useRenderIcon(AddFill)" @click="agvTask('返航', 3)">
                    返航
                </el-button>
                <el-button type="success" :icon="useRenderIcon(signOutBold)" @click="exportExcel()">
                    导出
                </el-button>
            </template>
            <template v-slot="{ size, dynamicColumns }">
                <pure-table ref="tableRef" :height="heightAuto" align-whole="center" row-key="Id" showOverflowTooltip
                    table-layout="auto" :loading="loading" :size="size" :data="dataList" :columns="dynamicColumns"
                    :border="true" :pagination="pagination" :paginationSmall="size === 'small' ? true : false"
                    class="auto-height-table" :header-cell-style="{
                        background: 'var(--el-fill-color-light)',
                        color: 'var(--el-text-color-primary)'
                    }" @page-size-change="handleSizeChange" @page-current-change="handleCurrentChange">
                    <template #operation="{ row }">
                        <el-button class="reset-margin" link type="danger" size="small"
                            :icon="useRenderIcon(outlineDelete)" @click="handleDelete(row)"
                            :disabled="row.status !== 0 && row.status !== 1 && row.status !== 5">
                            强制删除
                        </el-button>
                        <!-- <el-button class="reset-margin" link type="success" :size="size" :icon="useRenderIcon(baselineFindReplace)" 
            @click="replaceAgv(row)">
              更换车辆
            </el-button> -->
                        <!-- v-if="row.status === 0 && row.topping === 0" -->
                        <el-button class="reset-margin" link type="primary" size="small"
                            :icon="useRenderIcon(MessageBox)" @click="taskPrior(row, 1)"
                            v-if="row.status === 0 && row.topping === 0">
                            优先执行
                        </el-button>
                        <el-button class="reset-margin" link type="warning" size="small"
                            :icon="useRenderIcon(discardIcon)" @click="taskPrior(row, 0)"
                            v-if="row.status === 0 && row.topping > 0">
                            取消优先
                        </el-button>
                        <!-- <el-button class="reset-margin" link type="warning" :size="size" :icon="useRenderIcon(discardIcon)"
              @click="handleDiscard(row)">
              废弃
            </el-button> -->
                        <el-button class="reset-margin" link type="primary" size="small" :icon="useRenderIcon(Check)"
                            @click="complete(row)"
                            v-if="row.status === 0 || row.status === 1 || row.status === 4 || row.status === 5">
                            完成任务
                        </el-button>
                        <el-button class="reset-margin" link type="success" size="small" :icon="useRenderIcon(Refresh)"
                            @click="initialization(row)"
                            v-if="row.status === 0 || row.status === 1 || row.status === 4">
                            初始化
                        </el-button>
                    </template>
                </pure-table>
            </template>
        </PureTableBar>
    </div>
</template>

<!-- 任务初始化  以创建  执行中  and webscoket传输   -->

<script lang='ts' setup>
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { useDept } from "./utils/hook";
import { ref, watch, nextTick } from 'vue'

// iconify-icons
import AddFill from "@iconify-icons/ri/add-circle-line";
import outlineDelete from '@iconify-icons/ic/outline-delete';
import Search from "@iconify-icons/ep/search";
import Refresh from "@iconify-icons/ep/refresh";
import MessageBox from "@iconify-icons/ep/message-box";
import discardIcon from '@iconify-icons/quill/discard';
import signOutBold from '@iconify-icons/ph/sign-out-bold';
import Check from "@iconify-icons/ep/check";
import EpArrowDownBold from '@iconify-icons/ep/arrow-down-bold';
import EpArrowUpBold from '@iconify-icons/ep/arrow-up-bold';

const formRef = ref();
const tableRef = ref();
const tableKey = ref(0)
const searchBarZoom = ref(false)
const heightAuto = ref('40vh')

const changeHeight = () => {
    searchBarZoom.value = !searchBarZoom.value
    heightAuto.value = searchBarZoom.value ? '53vh' : '40vh'
    // nextTick(() => tableRef.value?.doLayout())
}

const correctingTime = (dateStr) => {
    const date = new Date(dateStr);

    // 计算时区偏移（防止 toISOString() 自动转 UTC）
    const timezoneOffset = date.getTimezoneOffset() * 60000; // 转为毫秒
    const adjustedDate = new Date(date.getTime() - timezoneOffset);

    // 转换为 ISO 格式，并去掉 'Z'（UTC 标识）
    const isoString = adjustedDate.toISOString().replace('Z', '');
    return isoString;
}

const pickerChange = () => {
    // form.dateRange === null ? form.begin = "" : form.begin = new Date(form.dateRange[0]).toLocaleString().replace('Z', '')
    // form.dateRange === null ? form.end = "" : form.end = new Date(form.dateRange[1]).toISOString().replace('Z', '')
    form.dateRange === null ? form.begin = "" : form.begin = correctingTime(form.dateRange[0])
    form.dateRange === null ? form.end = "" : form.end = correctingTime(form.dateRange[1])
}

const {
    columns,
    loading,
    dataList,
    openDialog,
    handleDelete,
    form,
    onSearch,
    resetForm,
    pagination,
    handleSizeChange,
    handleCurrentChange,
    statusSelect,
    searchCargo,
    userSelect,
    agvSelect,
    replaceAgv,
    taskPrior,
    exportExcel,
    agvTask,
    handleDiscard,
    taskOptions,
    initialization,
    complete,
    operationWidth
} = useDept();

//监听operationWidth
watch(operationWidth, (newValue, oldValue) => {
    // nextTick(() => tableRef.value.setHeaderSticky());
    // columns.value[12].width = newValue
    // tableRef.value?.doLayout()
    console.log(columns);
    tableKey.value++
});

</script>

<style lang="scss" scoped>
.search-form {
    :deep(.el-form-item) {
        margin-bottom: 12px;
    }
}

.el-dropdown {
    margin-right: 20px;
}

.widthExpansionAndContractionBut {
    position: absolute;
    top: 10px;
    right: 10px;
}

.searchBarZoomClass {
    height: 50px !important;
    overflow: hidden !important;
    // overflow-y: auto !important;
    // 添加动画
    // transition: all 0.3s ease !important;
}

.adminRole {
    display: flex;
    flex-direction: column;
    // height: 40vh !important;
    /* 或父容器明确的高度（如 calc(100vh - 60px)） */
}

.auto-height-table {
    flex-grow: 1;
    /* 关键：自动填充剩余空间 */
    min-height: 200px;
    /* 可选：设置最小高度 */
}
</style>